/**
 * @authors tanqichao
 * @date    2017-03-21 13:59:27
 * @module  新建客户（广告主）
 */

import { Form, Row, Col, Input, Button, Select, Table } from 'antd';
import { AccessControl } from '../../utils/common';
import ImgUpload from '../plugin/imgUpload';
import React, { Component } from 'react';
import Styles from './index.less';
import { connect } from 'dva';

const CreateForm = Form.create;
const Option = Select.Option;
const FormItem = Form.Item;
const formItemLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 10 }
};

class Customer extends Component {
	constructor(props) {
		super(props);
		this.state = {
			confirmDirty: false,
			licenseUrl: ''
		}
	}
  // 初始化
  componentDidMount = () => {

        this.props.dispatch({
          type: 'createCustomer/fetchSeller',
          payload: ''
        });
  }
	// 提交
	submit = (e) => {
		e.preventDefault();
		this.props.form.validateFieldsAndScroll((err, fieldsValue) => {
			this.validateRegisterCode();
			if (err) return;
			if (this.props.validateRegiterCode.status === 'error' || this.props.validateRegiterCode.status === 'validating') return;

			const params = Object.assign(fieldsValue, {
				licenseUrl: this.state.licenseUrl
			});

			console.log(params);
			this.props.dispatch({
      	type: 'createCustomer/submit',
      	payload: JSON.stringify(params)
      });
		})
	}

	// 搜索
	filterOperator = (input, option) => {
    return option.props.children.indexOf(input) > -1
  }

  // 密码二次校验
  handleConfirmBlur = (e) => {
    const value = e.target.value;

    this.setState({ confirmDirty: this.state.confirmDirty || !!value });
  }

  // 密码二次校验
  validatePassword = (rule, value, callback) => {
    const form = this.props.form;
    if (value && value !== form.getFieldValue('password')) {
      callback('两次密码输入不一致');
    } else {
      callback();
    }
  }

  // 上传营业执照
  handleLicenseUrl = (url) => {
  	console.log(url)
  	this.setState({
  		licenseUrl: url
  	})
  }

  // 注册号去重校验
  validateRegisterCode = () => {
  	const entName = this.props.form.getFieldValue('entName');
		const validateMethod = (status, help) => {
			this.props.dispatch({
	  		type: 'createCustomer/setRegisterCode',
	  		payload: { validateRegiterCode: { status: status, help: help } }
	  	})
		}
		if (!entName) {
			validateMethod('error', '请填写');
	  	return;
		}
		validateMethod('validating', '');
  	this.props.dispatch({
  		type: 'createCustomer/removeRptCode',
  		payload: JSON.stringify({ entName: entName })
  	})
  }

 // render
	render () {
    const permissionList = this.props.permissions;
		const { getFieldDecorator } = this.props.form;
		const { operatorList, sellerList } = this.props;
		const Options = operatorList.map(
      item => <Option key={item.id} value={item.id.toString()}>{item.name}</Option>
    );
    const sellerOptions = sellerList.map(
      item => <Option key={item.id} value={item.id.toString()}>{item.name}</Option>
    );

    const sellerObj = AccessControl(permissionList, 'dsp_agent_admin') ?
    (
      <div>
        <p className={Styles.title}>操作员</p>
        <FormItem {...formItemLayout}>
          {getFieldDecorator('opUserId', {
            initialValue: '',
            rules: [{
              required: true,
              message: '请填写'
            }]
          })(
            <Select
              showSearch
              notFoundContent="没有找到"
              placeholder="请分配一个操作员"
              filterOption={this.filterOperator}
            >
              { Options }
            </Select>
          )}
        </FormItem>

        <p className={Styles.title}>销售员</p>
				<FormItem {...formItemLayout}>
					{getFieldDecorator('sellerId', {
						initialValue: '',
						rules: [{
	          	required: true,
	          	message: '请填写'
	          }]
					})(
						<Select
			        // showSearch
			        notFoundContent="没有找到"
			        placeholder="请分配一个销售员"
			        // filterOption={this.filterOperator}
			      >
			        { sellerOptions }
			      </Select>
					)}
				</FormItem>
      </div>
    ): '';
		return (
			<Form className={Styles.createCustomer}>
        {sellerObj}


				<p className={Styles.title}>客户信息</p>

				<FormItem {...formItemLayout}>
					{getFieldDecorator('mail', {
						initialValue: '',
						rules: [{
            	required: true,
            	message: '请填写'
            }]
					})(
						<Input placeholder="邮箱" />
					)}
				</FormItem>

				<FormItem {...formItemLayout}>
					{getFieldDecorator('password', {
						initialValue: '',
						rules: [{
              min: 8,
              message: '密码不少于8位'
            }, {
            	required: true,
            	message: '请填写'
            }]
					})(
						<Input type="password" placeholder="密码" />
					)}
				</FormItem>

				<FormItem {...formItemLayout}>
					{getFieldDecorator('confirmPassword', {
						initialValue: '',
						rules: [{
            	required: true,
            	message: '请填写'
            }, {
            	validator: this.validatePassword
            }]
					})(
						<Input type="password" placeholder="请再次输入密码" onBlur={this.handleConfirmBlur} />
					)}
				</FormItem>

				<p className={Styles.title}>客户资料</p>

				<FormItem {...formItemLayout}
          validateStatus={this.props.validateRegiterCode.status}
          help={this.props.validateRegiterCode.help}
        >
					{getFieldDecorator('entName', {
						initialValue: '',
						rules: [{
            	required: true,
            	message: '请填写'
            }]
					})(
						<Input placeholder="公司全称" onBlur={this.validateRegisterCode} />
					)}
				</FormItem>

				<FormItem
					{...formItemLayout}
				>
					{getFieldDecorator('registerCode')(
						<Input placeholder="营业执照注册号" />
					)}
				</FormItem>

				<FormItem {...formItemLayout}>
					{getFieldDecorator('address', {
						initialValue: '',
						rules: [{
            	required: true,
            	message: '请填写'
            }]
					})(
						<Input placeholder="公司地址" />
					)}
				</FormItem>

				<FormItem {...formItemLayout}>
					{getFieldDecorator('licenseUrl', {
						initialValue: '',
						rules: [{
            	required: false,
            	message: '请填写'
            }]
					})(
						<ImgUpload uploadText="上传营业执照" onComplete={this.handleLicenseUrl} />
					)}
				</FormItem>

				<p className={Styles.title}>联系人信息</p>

				<FormItem {...formItemLayout}>
					{getFieldDecorator('contactName', {
						initialValue: '',
						rules: [{
            	required: true,
            	message: '请填写'
            }]
					})(
						<Input placeholder="联系人姓名" />
					)}
				</FormItem>

				<FormItem {...formItemLayout}>
					{getFieldDecorator('contactTel', {
						initialValue: '',
						rules: [{
            	required: true,
            	message: '请填写'
            }]
					})(
						<Input placeholder="手机号码" />
					)}
				</FormItem>

				<FormItem {...formItemLayout}>
					{getFieldDecorator('contactQQ', {
						initialValue: '',
						rules: [{
            	required: true,
            	message: '请填写'
            }]
					})(
						<Input placeholder="qq号码" />
					)}
				</FormItem>

				<FormItem {...formItemLayout}>
					{getFieldDecorator('contactWX', {
						initialValue: '',
					})(
						<Input placeholder="微信号" />
					)}
				</FormItem>

				<p className={Styles.title}>备注</p>
				<FormItem {...formItemLayout}>
					{getFieldDecorator('remark', {
						initialValue: '',
					})(
						<Input className={Styles.remark} type="textarea" placeholder="请输入备注信息~" maxLength={1300} />
					)}
				</FormItem>

				<Button type="primary" size="large" onClick={this.submit} className={Styles.submitBtn}>提交审核</Button>
			</Form>
		)
	}
}

export default connect((state) => {
  const { permissions } = state.indexPage;
	const { operatorList, sellerList, validateRegiterCode } = state.createCustomer;
	return {
		operatorList,
    sellerList,
		validateRegiterCode,
    permissions
	}
})(CreateForm({})(Customer));
